{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "is_executing": true
    }
   },
   "source": [
    "\"\"\"卷积神经网络lenet，由两个部分构成：卷积编码器CNN和全连接层linear构成\"\"\"\n",
    "#code:https://zh.d2l.ai/chapter_convolutional-neural-networks/lenet.html\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from click.core import F\n",
    "from d2l.torch import d2l\n",
    "\n",
    "\n",
    "class Reshape(nn.Module):\n",
    "    def forward(self, x):\n",
    "        return x.view(-1,1,28,28) #bathdize=auto,channel=1,width=28,height=28;\n",
    "\n",
    "\n",
    "def evaluate_accuracy_gpu(net, data_iter, device=None): #@save\n",
    "    \"\"\"使用GPU计算模型在数据集上的精度\"\"\"\n",
    "    if isinstance(net, nn.Module):\n",
    "        net.eval()  # 设置为评估模式\n",
    "        if not device:\n",
    "            device = next(iter(net.parameters())).device\n",
    "    # 正确预测的数量，总预测的数量\n",
    "    metric = d2l.Accumulator(2)\n",
    "    with torch.no_grad():\n",
    "        for X, y in data_iter:\n",
    "            if isinstance(X, list):\n",
    "                # BERT微调所需的（之后将介绍）\n",
    "                X = [x.to(device) for x in X]\n",
    "            else:\n",
    "                X = X.to(device)\n",
    "            y = y.to(device)\n",
    "            metric.add(d2l.accuracy(net(X), y), y.numel())\n",
    "    return metric[0] / metric[1]\n",
    "#@save\n",
    "def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):\n",
    "    \"\"\"用GPU训练模型(在第六章定义)\"\"\"\n",
    "    def init_weights(m):\n",
    "        if type(m) == nn.Linear or type(m) == nn.Conv2d:\n",
    "            nn.init.xavier_uniform_(m.weight)\n",
    "    net.apply(init_weights)\n",
    "    print('training on', device)\n",
    "    net.to(device)\n",
    "    optimizer = torch.optim.SGD(net.parameters(), lr=lr)\n",
    "    loss = nn.CrossEntropyLoss()\n",
    "    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],\n",
    "                            legend=['train loss', 'train acc', 'test acc'])\n",
    "    timer, num_batches = d2l.Timer(), len(train_iter)\n",
    "    for epoch in range(num_epochs):\n",
    "        # 训练损失之和，训练准确率之和，样本数\n",
    "        metric = d2l.Accumulator(3)\n",
    "        net.train()\n",
    "        for i, (X, y) in enumerate(train_iter):\n",
    "            timer.start()\n",
    "            optimizer.zero_grad()\n",
    "            X, y = X.to(device), y.to(device)\n",
    "            y_hat = net(X)\n",
    "            l = loss(y_hat, y)\n",
    "            l.backward()\n",
    "            optimizer.step()\n",
    "            with torch.no_grad():\n",
    "                metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])\n",
    "            timer.stop()\n",
    "            train_l = metric[0] / metric[2]\n",
    "            train_acc = metric[1] / metric[2]\n",
    "            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:\n",
    "                animator.add(epoch + (i + 1) / num_batches,\n",
    "                             (train_l, train_acc, None))\n",
    "        test_acc = evaluate_accuracy_gpu(net, test_iter)\n",
    "        animator.add(epoch + 1, (None, None, test_acc))\n",
    "    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '\n",
    "          f'test acc {test_acc:.3f}')\n",
    "    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '\n",
    "          f'on {str(device)}')\n",
    "\n",
    "\n",
    "batch_size = 256\n",
    "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)\n",
    "\n",
    "if __name__==\"__main__\":\n",
    "    net = torch.nn.Sequential(\n",
    "        # 1,第一部分，cnn\n",
    "        Reshape(), nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, padding=2), nn.Sigmoid(),\n",
    "        # 第一层,最后加入sigmoid是为了非线性性\n",
    "        nn.AvgPool2d(kernel_size=2, stride=2),\n",
    "        nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5), nn.Sigmoid(),  # 卷积的核心是高宽是一直在减少的，通道是一直在增加的。\n",
    "        nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(),\n",
    "        # AvgPool2d output shape:torch.Size([1, 16, 5, 5])，然后经过flattern是指将全部拉为一个维度\n",
    "\n",
    "        # 2.第二部分，全连接linear\n",
    "        nn.Linear(in_features=16 * 5 * 5, out_features=120), nn.Sigmoid(),  # 其中16是通道数（比如卷积层的输出通道数），而5x5可能是某个特征图的尺寸\n",
    "        nn.Linear(in_features=120, out_features=84), nn.Sigmoid(),  # torch.Size([1, 120])——。84\n",
    "        nn.Linear(in_features=84, out_features=10)  ##torch.Size([1, 84])——。10，          MLP的核心就是一直在压缩压缩\n",
    "\n",
    "    )\n",
    "\n",
    "    x=torch.randn(size=(1, 1,28, 28),dtype=torch.float32)\n",
    "    for layer in net:\n",
    "        x = layer(x)  #注意不是net（x）,而是对每一层进行输入计算shape，查看调用关系\n",
    "        print(layer.__class__.__name__,\"output shape: \\t\",x.shape)\n",
    "\n",
    "    lr, num_epochs = 0.9, 10\n",
    "    train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())\n",
    "\n",
    "\n",
    "# class LeNet(nn.Module):\n",
    "#     def __init__(self):\n",
    "#         super(LeNet, self).__init__()\n",
    "#         self.conv1 = nn.Conv2d(1, 6, 5)\n",
    "#         self.pool = nn.MaxPool2d(2, 2)\n",
    "#         self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "#         self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "#         self.fc2 = nn.Linear(120, 84)\n",
    "#         self.fc3 = nn.Linear(84, 10)\n",
    "#         self.relu = nn.ReLU()\n",
    "#         self.dropout = nn.Dropout(0.5)\n",
    "#         self.softmax = nn.LogSoftmax(dim=1)\n",
    "#         self.sigmoid = nn.Sigmoid()\n",
    "#\n",
    "#     def forward(self, x):\n",
    "#         x = self.pool(F.relu(self.conv1(x)))\n",
    "#         x = self.pool(F.relu(self.conv2(x)))\n",
    "#         x = x.view(-1, 16 * 5 * 5)\n",
    "#         x = self.relu(self.fc1(x))\n",
    "#         x = self.relu(self.fc2(x))\n",
    "#         x = self.fc3(x)\n",
    "#         x = self.sigmoid(x)\n",
    "#         return x\n",
    "#\n"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "1268e439552273e"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
